import base from './base';
import axios from './http';
import { sha256 } from 'js-sha256';
import { Utils } from '@/common/utils.js';
import { useCommonStore, useCommonApiStore } from '@/store/main';
import type { AxiosResponse } from 'axios'
import type { SwitchUpdateFnParamsType, ResponseType } from '@/request/apiType'


type AxiosResponseType = Promise<AxiosResponse<any>>

/**
 * 获取系统信息
 */
export function systemNameRqs(): Promise<ResponseType> {
	const res = {
		code: 0,
		data: [
			{
				"env": "tap_dev",
				"system_id": "_all_",
				"system_name": "交易推送中台"
			}
		],
		msg: "success"
	}
	return Promise.resolve(res)
}

/**
 * 用户登录
 */
interface SignInParamsType {
	user_name: string
	nonce: string
	ts: number | string
	sign: string
}
export function signInRqs<T extends SignInParamsType>({
	user_name,
	nonce,
	ts,
	sign
}: T): Promise<ResponseType> {
	const $store = useCommonStore()
	let isValidUserFlag = false
	let password = ''
	let userType = 1
	let isNeedModifyPasswd = false
	const res: ResponseType = {
		code: 0,
		data: [],
		msg: "success"
	}
	$store.userList.forEach(item => {
		if(item.userName === user_name) {
			isValidUserFlag = true
			password = item.password
			userType = item.userType
			isNeedModifyPasswd = item.is_need_modify_passwd
		}
	})
	if(!isValidUserFlag) {
		res.code = -1
		res.msg = '用户不存在'
		return Promise.resolve(res)
	}

	const hash = sha256.create()
	hash.update(`${user_name}_${password}_${nonce}_${ts}`)
	const signHex = hash.hex()

	if(sign !== signHex) {
		res.code = -1
		res.msg = '密码错误'
		return Promise.resolve(res)
	}
		
	res.code = 0
	res.msg = 'success'
	res.data.push({
		"is_need_modify_passwd": isNeedModifyPasswd,
		"token": "Bearer xxx",
		"ttl": 864000,
		"user_type": userType,
	})

	return Promise.resolve(res)
}

/**
 * 自动登录
 */
interface ReSignInParamsType {
	user_name: string
}
export function reSignInRqs(params: ReSignInParamsType): Promise<ResponseType> {
	const res = {
		code: 0,
		data: [
			{
				"is_need_modify_passwd": false,
				"token": "Bearer xxx",
				"ttl": 1800,
				"user_type": params.user_name === 'guocj' ? 999999 : 0
			}
		],
		msg: "success"
	}
	return Promise.resolve(res)
}

/**
 * 设置密码/修改密码
 */
interface SetPasswordParamsType {
	user_name: string
	nonce: string
	ts: number | string
	secret_key: string
	sign: string
}
export function setPasswordRqs(params: SetPasswordParamsType): Promise<ResponseType> {
	const $store = useCommonStore()
	$store.setUserStatus(false)
	const res = {
		code: 0,
		msg: 'success',
		data: []
	}
	return Promise.resolve(res)
}

// 服务管理
export function serviceListRqs(params: { sys_name: string }): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const data = $storeApi.getServiceList(params)
	const res = {
		code: 0,
		msg: 'success',
		data
	}
	return Promise.resolve(res)
}
export function serviceListDetailsRqs(params: {
	sys_name: string
	service_name: string
	page_no: number
	page_size: number
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const {data, total} = $storeApi.getServiceListDetail(params)
	const res = {
		code: 0,
		msg: 'success',
		total,
		data
	}
	return Promise.resolve(res)
}
export function serviceListDetailsAddRqs(params: {
	sys_name: string
	service_name: string
	[property: string]: any
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	let code = -1, total = 0, data: any[] = [], msg = 'success! 添加成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const serviceListData = item.serviceList!
			const id = serviceListData.length + 1
			const o = {
				id,
				name: params.name,
				version: params.version,
				build_info: params.build_info,
				deploy_type: params.deploy_type,
				is_primary: params.is_primary,
				weight: params.weight,
				is_online: params.is_online,
				is_enable: false,
				listen_addr: params.listen_addr,
				nat_addr: params.nat_addr,
				listen_addr_admin: params.listen_addr_admin,
				start_timeStamp: Utils.getDate().getFullDateTime
			}
			serviceListData.splice(0, 0, o)
			code = 0
			total = serviceListData.length
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}
export function serviceListDetailsEditRqs(params: {
	sys_name?: string
	service_name?: string
	[property: string]: any
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	const id = params.id
	let isRejectFlag = false, 
		res: ResponseType = {code: -1, msg: '', data: [], total: -1}, 
		code = -1, 
		total = 0, 
		data: any[] = [], 
		msg = 'success! 编辑成功'
	if(params.name === '') {
		msg = `error:服务实例名称不能为空，[name = " "]`
		isRejectFlag = true
	}
	res = {code, msg, data, total} 
	if(isRejectFlag) return Promise.reject(res)

	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const serviceListData = item.serviceList!
			let _index = -1, o: any = {}
			serviceListData.forEach((itemInner, indexInner) => {
				if(itemInner.id === id) {
					delete params.sys_name
					delete params.service_name
					_index = indexInner
					o = {...itemInner, ...params}
				}
			})
			serviceListData.splice(_index, 1)
			serviceListData.splice(0, 0, o)
			code = 0
			total = serviceListData.length
		}
	})
	res = {code, msg, data, total} 
	return Promise.resolve(res)
}
export function serviceListDetailsDeleteRqs(params: {
	id: number[] 
	sys_name: string
	service_name: string
}) {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	const ids = params.id
	let code = -1, total = 0, data: any[] = [], msg = 'success! 删除成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const serviceListData = item.serviceList!
			ids.forEach(id => {
				let _index = -1
				serviceListData.forEach((itemInner, indexInner) => {
					if(id === itemInner.id) _index = indexInner
				})
				serviceListData.splice(_index, 1)
			})
			code = 0
			total = serviceListData.length
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}
export function serviceSwitchOnRqs(params: SwitchUpdateFnParamsType): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	const ids = params.id
	let code = -1, total = 0, data: any[] = [], msg = 'success! 启用成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const serviceListData = item.serviceList!
			ids.forEach(id => {
				serviceListData.forEach(itemInner => {
					if(id === itemInner.id) itemInner.is_enable = true
				})
			})
			code = 0
			total = 0
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}
export function serviceSwitchOffRqs(params: SwitchUpdateFnParamsType): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	const ids = params.id
	let code = -1, total = 0, data: any[] = [], msg = 'success! 启用成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const serviceListData = item.serviceList!
			ids.forEach(id => {
				serviceListData.forEach(itemInner => {
					if(id === itemInner.id) itemInner.is_enable = false
				})
			})
			code = 0
			total = 0
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}

// 配置管理-扩展配置
// 获取主版本配置
export function serviceDycofigMainRqs(params: {
	sys_name: string
	service_name: string
	page_no: number
	page_size: number
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const {data, total} = $storeApi.getServiceDycofigMainList(params)
	const res = {
		code: 0,
		msg: 'success',
		total,
		data
	}
	return Promise.resolve(res)
}
// 获取灰度版本配置
export function serviceDycofigGrayRqs(params: {
	sys_name: string
	service_name: string
	page_no: number
	page_size: number
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const {data, total} = $storeApi.getServiceDycofigGrayList(params)
	const res = {
		code: 0,
		msg: 'success',
		total,
		data
	}
	return Promise.resolve(res)
}
// 编辑主版本配置
export function serviceDycofigMainEditRqs(params: {
	sys_name?: string
	service_name?: string
	key: string
	value: string
	[property: string]: any
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const key = params.key
	const value = params.value
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	let isRejectFlag = false, 
		res: ResponseType = {code: -1, msg: '', data: [], total: -1}, 
		code = -1, 
		total = 0, 
		data: any[] = [], 
		msg = 'success! 编辑成功'
	if(value === '') {
		msg = `error:value的值不能为空，[value = " "]`
		isRejectFlag = true
	}
	res = {code, msg, data, total} 
	if(isRejectFlag) return Promise.reject(res)
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const mainExpandConf = item.mainExpandConf!
			let _index = -1, o: any = {}
			mainExpandConf.forEach((itemInner, indexInner) => {
				if(itemInner.key === key) {
					delete params.sys_name
					delete params.service_name
					_index = indexInner
					o = {...itemInner, ...params}
				}
			})
			mainExpandConf.splice(_index, 1)
			mainExpandConf.splice(0, 0, o)
			code = 0
			total = mainExpandConf.length
		}
	})
	res = {code, msg, data, total} 
	return Promise.resolve(res)
}
// 新增主版本配置
export function serviceDycofigMainAddRqs(params: {
	sys_name: string
	service_name: string
	key: string
	value: string
	[property: string]: any
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const key = params.key
	const value = params.value
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	let isRejectFlag = false
	let code = -1, total = 0, data: any[] = [], msg = 'success! 添加成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const mainExpandConf = item.mainExpandConf!
			mainExpandConf.forEach(itemInner => {
				if(itemInner.key === key) {
					isRejectFlag = true
					msg = `error:value的值不能为空，[value = " "]`
				}
			})
			if(isRejectFlag) return Promise.reject(res)
			const o = {
				key,
				value
			}
			mainExpandConf.splice(0, 0, o)
			code = 0
			total = mainExpandConf.length
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}
// 编辑灰度主版本配置
export function serviceDycofigGrayEditRqs(params: {
	sys_name?: string
	service_name?: string
	key: string
	value: string
	[property: string]: any
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const key = params.key
	const value = params.value
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	let isRejectFlag = false, 
		res: ResponseType = {code: -1, msg: '', data: [], total: -1}, 
		code = -1, 
		total = 0, 
		data: any[] = [], 
		msg = 'success! 编辑成功'
	if(value === '') {
		msg = `error:value的值不能为空，[value = " "]`
		isRejectFlag = true
	}
	res = {code, msg, data, total} 
	if(isRejectFlag) return Promise.reject(res)
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const grayExpandConf = item.grayExpandConf!
			let _index = -1, o: any = {}
			grayExpandConf.forEach((itemInner, indexInner) => {
				if(itemInner.key === key) {
					delete params.sys_name
					delete params.service_name
					_index = indexInner
					o = {...itemInner, ...params}
				}
			})
			grayExpandConf.splice(_index, 1)
			grayExpandConf.splice(0, 0, o)
			code = 0
			total = grayExpandConf.length
		}
	})
	res = {code, msg, data, total} 
	return Promise.resolve(res)
}
// 新增灰度主版本配置
export function serviceDycofigGrayAddRqs(params: {
	sys_name: string
	service_name: string
	key: string
	value: string
	[property: string]: any
}): Promise<ResponseType> {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const key = params.key
	const value = params.value
	const instance_id = params.instance_id
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	let isRejectFlag = false
	let code = -1, total = 0, data: any[] = [], msg = 'success! 添加成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const grayExpandConf = item.grayExpandConf!
			grayExpandConf.forEach(itemInner => {
				if(itemInner.key === key) {
					isRejectFlag = true
					msg = `error:value的值不能为空，[value = " "]`
				}
			})
			if(isRejectFlag) return Promise.reject(res)
			const o = {
				key,
				value,
				instance_id
			}
			grayExpandConf.splice(0, 0, o)
			code = 0
			total = grayExpandConf.length
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}
// 删除主板本配置
export function serviceDycofigMainDeleteRqs(params: {
	sys_name: string
	service_name: string
	key: string[]
}) {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	const keys = params.key
	let code = -1, total = 0, data: any[] = [], msg = 'success! 删除成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const mainExpandConf = item.mainExpandConf!
			keys.forEach(key => {
				let _index = -1
				mainExpandConf.forEach((itemInner, indexInner) => {
					if(key === itemInner.key) _index = indexInner
				})
				mainExpandConf.splice(_index, 1)
			})
			code = 0
			total = mainExpandConf.length
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}
// 删除灰度版本配置
export function serviceDycofigGrayDeleteRqs(params: {
	sys_name: string
	service_name: string
	key: string[]
}) {
	const $storeApi = useCommonApiStore()
	const systemServiceInfo = $storeApi.systemServiceInfo
	const sys_name = params.sys_name
	const service_name = params.service_name
	const serviceList = systemServiceInfo[sys_name as keyof typeof systemServiceInfo]
	const keys = params.key
	let code = -1, total = 0, data: any[] = [], msg = 'success! 删除成功'
	serviceList.forEach(item => {
		if(item.service_name === service_name) {
			const grayExpandConf = item.grayExpandConf!
			keys.forEach(key => {
				let _index = -1
				grayExpandConf.forEach((itemInner, indexInner) => {
					if(key === itemInner.key) _index = indexInner
				})
				grayExpandConf.splice(_index, 1)
			})
			code = 0
			total = grayExpandConf.length
		}
	})
	const res = {code, msg, data, total} 
	return Promise.resolve(res)
}


// 

// // 系统查询
// export function getSystemInfo(params) {
// 	const total = params.customTotal || 10
// 	const n = 0, data = [], endNum = params.page_no * params.page_size
// 	const s = (params.page_no - 1) * params.page_size, 
// 		e = endNum > total ? total : endNum

// 	for(let i = s; i < e; i++) {
// 		data.push({
// 			sys_id: `${i + 1}`,
// 			sys_name: `测试系统_test_${n + i + 1}`
// 		})
// 	}
// 	const res = {
// 		code: 0,
// 		msg: "success",
// 		data,
// 		total
// 	}
// 	return Promise.resolve(res)
// }
// // 流控
// export function getFlowCtrListRqs(params) {
// 	const $storeApi = useCommonApiStore()
// 	let res = {}
// 	if($storeApi.flowCtrInfo.data.length) {
// 		res = $storeApi.flowCtrInfo
// 		return Promise.resolve(res)
// 	}
// 	const total = params.customTotal || 12
// 	let n = 0, t = total, data = []
// 	for(let i = 0; i < t; i++) {
// 		data.push({
// 			"sys_id": `${params.sys_id}`,
// 			"id": `${n + i + 1}`,
// 			"alarm_rate": "99",
// 			"desc": `描述${n + i + 1}`,
// 			"filters": [
// 				{
// 					"k": "ip_group",
// 					"v": "aa"
// 				}, {
// 					"k": "fund_account",
// 					"v": "haoduoyu"
// 				}, {
// 					"k": "api_group",
// 					"v": "hello"
// 				}
// 			],
// 			"filters_orig": "",
// 			"is_enable":false,
// 			"priority": Utils.getRandomInt(1, 110),
// 			"ctime":"2024-04-22 20:07:58",
// 			"rate": Utils.getRandomInt(1, 99),
// 			"utime":"2024-05-23 21:15:12"
// 		})
// 	}
	
// 	res = {
// 		"code": 0,
// 		"msg": "success",
// 		data,
// 		total
// 	}
// 	$storeApi.setFlowCtrInfo(params.sys_id, res)
// 	return Promise.resolve(res)
// }

// export function getFlowCtrRulesAPIListRqs(params) {
// 	const total = params.customTotal || 12
// 	let n = 0, t = total, data = []
// 	const ApiGroupList = []
// 	for(let i = 0; i < t; i++) {
// 		const apiGroupName = `api_groupName_${n + i + 1}`
// 		const apiGroupNameDesc = `API描述测试${Utils.generateMixStrFn()}`
// 		const apiGroupNameObj = {
// 			group_name: apiGroupName,
// 			desc: apiGroupNameDesc
// 		}
// 		ApiGroupList.push(apiGroupNameObj)
// 		data.push(apiGroupNameObj)
// 	}

// 	// api分组列表
// 	const $storeApi = useCommonApiStore()
// 	$storeApi.setFlowCtrApiGroupList(ApiGroupList)
	
// 	const res = {
// 		"code": 0,
// 		"msg": "success",
// 		data,
// 		total
// 	}
// 	return Promise.resolve(res)
// }

// export function getFlowCtrRulesIPListRqs(params) {
// 	const total = params.customTotal || 12
// 	let n = 0, t = total, data = []
// 	const IpGroupList = []
// 	for(let i = 0; i < t; i++) {
// 		const iPGroupName = `ip_groupName_${n + i + 1}`
// 		const iPGroupNameDesc = `IP分组的描述测试${Utils.generateMixStrFn()}`
// 		const iPGroupNameObj = {
// 			group_name: iPGroupName,
// 			desc: iPGroupNameDesc
// 		}

// 		IpGroupList.push(iPGroupNameObj)
// 		data.push(iPGroupNameObj)
// 	}

// 	// ip分组列表
// 	const $storeApi = useCommonApiStore()
// 	$storeApi.setFlowCtrIpGroupList(IpGroupList)
	
// 	const res = {
// 		"code": 0,
// 		"msg": "success",
// 		data,
// 		total
// 	}
// 	return Promise.resolve(res)
// }

// // API详情
// export function getApiDetailListRqs(params) {
// 	const total = params.customTotal || 3
// 	let n = 0, t = total, data = []
// 	for(let i = 0; i < t; i++) {
// 		data.push({
// 			"id": `${n + i + 1}`,
// 			"service_name": `${params.group_name}__${n + i + 1}`,
// 			"api_name": `api_${n + i + 1}`,
// 			"is_enable": (n % 3) ? true : false,
// 			"ctime":"2024-04-22 20:07:58",
// 			"utime":"2024-05-23 21:15:12"
// 		})
// 	}
	
// 	const res = {
// 		"code": 0,
// 		"msg": "success",
// 		data,
// 		total
// 	}
// 	return Promise.resolve(res)
// }


// // https://echo.apifox.com api测试
// export function testGetRqs(params) {
// 	return axios.get(base.testGet, params);
// }
// export function testPostRqs(params) {
// 	return axios.post(base.testPost, params);
// }

/*
export function systemNameRqs(): AxiosResponseType {
	return axios.get(base.systemName);
}

export function signInRqs(params: SignInParamsType): AxiosResponseType {
	return axios.post(base.signIn, params);
}

export function reSignInRqs(params): AxiosResponseType {
	return axios.post(base.reSignIn, params);
}

export function setPasswordRqs(params: SetPasswordParamsType): AxiosResponseType {
	return axios.post(base.setPassword, params);
}
*/